<template>
	<el-dialog
		title="图片验证码"
		:visible.sync="visible"
		width="431px"
		custom-class="captcha"
		:close-on-click-modal="false"
		append-to-body
		@close="hide"
	>
		<div>
			<el-form ref="form" :model="form" :rules="rules" @submit.native.prevent>
				<el-form-item prop="verifyCode">
					<div class="row">
						<el-input
							placeholder="请输入图片验证码"
							v-model="form.verifyCode"
							maxlength="4"
							ref="input"
							clearable
							@keydown.enter.native="next"
						></el-input>

						<div class="svg" @click="captcha" v-html="svg" v-if="svg"></div>
						<div class="svg" @click="captcha" v-else>
							<i class="el-icon-refresh-right">点击刷新</i>
						</div>
					</div>
				</el-form-item>
			</el-form>
		</div>

		<span slot="footer" class="dialog-footer">
			<el-button type="primary" @click="next" size="medium" v-loading="loading"
				>确 定</el-button
			>
		</span>
	</el-dialog>
</template>
<script>
export default {
	data() {
		return {
			visible: false,
			form: {
				captchaId: '',
				verifyCode: ''
			},
			svg: '',
			phone: '',
			loading: false,
			rules: {
				verifyCode: [
					{
						required: true,
						message: '图片验证码不能为空',
						trigger: 'change'
					}
				]
			}
		};
	},

	methods: {
		open(phone) {
			this.visible = true;
			this.phone = phone;

			this.$nextTick(() => {
				this.captcha();
				this.$refs.input.focus();
			});
		},
		hide() {
			this.$refs.form.resetFields();

			this.visible = false;
		},
		captcha() {
			// this.form.verifyCode = '';

			this.$service.common
				.captcha({
					height: 40,
					width: 120
				})
				.then(res => {
					this.svg = res.data;
					this.form.captchaId = res.captchaId;
				})
				.catch(() => {
					// this.$message.error(err);
					this.$message.error('请勿频繁获取验证码');
				});
		},
		next() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.$service.common
						.smsCode({
							...this.form,
							phone: this.phone
						})
						.then(() => {
							this.$message.success('发送短信成功');
							this.$emit('callback', true);
							this.hide();
						})
						.catch(err => {
							this.$message.error(err);
						})
						.done(() => {
							this.loading = false;
							this.captcha();
						});
				}
			});
		}
	}
};
</script>
<style lang="stylus" scoped>
.captcha {
	.row {
		display: flex;

		.el-input {
			flex: 1;
			margin-right: 10px;
		}

		.svg {
			display: block;
			height: 40px;
			width: 120px;
			border-radius: 5px;
			border: 1px solid #DCDFE6;
			box-sizing: border-box;
			transition .3s
			overflow hidden
			cursor pointer
			svg {
				height 100%
			}
			.el-icon-refresh-right {
				width 100%
				height 100%
				font-size 12px
				display flex
				justify-content center
				align-items center
				cursor pointer
				transition .3s
				&:before {
					font-size 14px
					margin-right 4px
				}
				&:hover {
					color $main-color
				}
			}
			&:hover {
				border-color: $main-color;
			}
		}
	}
}
</style>
